package com.sinosoft.hydra.um.domain.permission;

import cn.com.sinux.spring.utils.ValidatorUtils;
import com.alibaba.fastjson.annotation.JSONField;
import com.sinosoft.hydra.um.constant.BaseConstant;
import org.apache.commons.lang.StringUtils;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;

import javax.persistence.*;
import java.util.*;

;

/**
 * created:2014/12/03
 * <p>用户表</p>
 *
 * @author oujianlin@sinosoft.co
 */
@Entity
@DynamicInsert(true)
@DynamicUpdate(true)
@Table(name = "UM_SYS_USER_MEMBER")
public class SysUserMember extends IdEntity implements java.io.Serializable {

    private static final long serialVersionUID = 1531492635701976701L;
    private String userName;
    private String userPassword;
    private String userSalt;
    private List<SysRole> sysRoles = new ArrayList<SysRole>();
    private Integer available;
    private String email;
    private String userHead;
    private String alias;
    @JSONField(format = "yyyy-MM-dd")
    private Date createTime;
    private String userNumber;
    private List<SysOrganizationUser> sysOrganizationUsers;
    private List<TDocumentCopy> visibleDocs;
    private Integer orderNo;
    private String ipAddress;

    @Transient
    public List<SysOrganization> getSysOrganizations(){
        List<SysOrganization> sysOrganizations = new ArrayList<SysOrganization>();
        if(ValidatorUtils.isArrayNotEmpty(sysOrganizationUsers)){
            for(SysOrganizationUser sysOrganizationUser : sysOrganizationUsers){
                sysOrganizations.add(sysOrganizationUser.getSysOrganization());
            }
        }
        return sysOrganizations;
    }

    @Transient
    public String getRolePermissions() {
        List<String> ids = new ArrayList<String>();
        if (ValidatorUtils.isArrayNotEmpty(this.getSysRoles())) {
            for (SysRole sysRole : getSysRoles()) {
                ids.add(sysRole.getId());
            }
        }
        return StringUtils.join(ids, ",");
    }

    @Column(name = "USER_NUMBER")
    public String getUserNumber() {
        return userNumber;
    }

    public void setUserNumber(String userNumber) {
        this.userNumber = userNumber;
    }

    @Column(name = "USER_HEAD")
    public String getUserHead() {
        return userHead;
    }

    public void setUserHead(String userHead) {
        this.userHead = userHead;
    }

    @OneToMany
    @JoinColumn(name = "USER_ID")
    public List<SysOrganizationUser> getSysOrganizationUsers() {
        return sysOrganizationUsers;
    }

    public void setSysOrganizationUsers(List<SysOrganizationUser> sysOrganizationUsers) {
        this.sysOrganizationUsers = sysOrganizationUsers;
    }

    /**
     * 创建时间
     *
     * @return Date
     */
    @Column(name = "CREATE_TIME")
    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    /**
     * 昵称
     *
     * @return String
     */
    @Column(name = "ALIAS")
    public String getAlias() {
        return alias;
    }

    public void setAlias(String alias) {
        this.alias = alias;
    }

    /**
     * 邮箱
     *
     * @return String
     */
    @Column(name = "EMAIL")
    public String getEmail() {
        return email;
    }

    /**
     * 手机
     *
     * @return String
     */
    @Column(name = "MOBILE")
    public String getMobile() {
        return mobile;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public void setMobile(String mobile) {
        this.mobile = mobile;
    }

    private String mobile;

    /**
     * 1-可用 0-不可用
     *
     * @return String
     */
    @Column(name = "AVAILABLE")
    public Integer getAvailable() {
        return available;
    }

    public void setAvailable(Integer available) {
        this.available = available;
    }

    public SysUserMember() {

    }

    public SysUserMember(String id, String userName) {
        this.userName = userName;
        this.id = id;
    }

    /**
     * 用户名
     *
     * @return String
     */
    @Column(name = "USER_NAME")
    public String getUserName() {
        return this.userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    /**
     * 用户密码
     *
     * @return String
     */
    @Column(name = "USER_PASSWORD")
    @JSONField(serialize = false)
    public String getUserPassword() {
        return this.userPassword;
    }

    public void setUserPassword(String userPassword) {
        this.userPassword = userPassword;
    }

    /**
     * 用户密盐
     *
     * @return String
     */
    @Column(name = "USER_SALT")
    public String getUserSalt() {
        return this.userSalt;
    }

    public void setUserSalt(String userSalt) {
        this.userSalt = userSalt;
    }

//    @ManyToMany(fetch = FetchType.LAZY, mappedBy = "sysUserMembers")
    @ManyToMany(fetch=FetchType.LAZY)
    @JoinTable(name = "UM_SYS_ROLE_USER"	//中间表的表名
            , joinColumns = @JoinColumn(name = "USER_ID")	//指向本端的外键
            , inverseJoinColumns = @JoinColumn(name = "ROLE_ID"))	//指向对方端的外键
    @JSONField(serialize = false)
    public List<SysRole> getSysRoles() {
        return sysRoles;
    }

    public void setSysRoles(List<SysRole> sysRoles) {
        this.sysRoles = sysRoles;
    }

    @Transient
    public List<SysResource> getMenu() {
         List<SysResource> sysResources = new ArrayList<SysResource>();
         for(SysResource sysResource : getSysResources()){
             if(BaseConstant.ResourceType.MENU.getValue().equals(sysResource.getResourceType())){
                 sysResources.add(sysResource);
             }
         }
        Collections.sort(sysResources, new Comparator<SysResource>() {

            public int compare(SysResource sysResource, SysResource sysResource2) {
                return sysResource.getOrderNo().compareTo(sysResource2.getOrderNo());
            }
        });
        return sysResources;
    }

    @Transient
    public List<SysResource> getSysResources() {
        Map<String, SysResource> resourceMap = new HashMap<String, SysResource>();
        if(ValidatorUtils.isArrayNotEmpty(sysRoles)){
            for(SysRole role : sysRoles){
                if(ValidatorUtils.isArrayNotEmpty(role.getSysResources())){
                    for(SysResource sysResource : role.getSysResources()){
                        sysResource.setSysResource(null);
                        resourceMap.put(sysResource.getId(), sysResource);
                    }
                }
            }
        }
        return new ArrayList<SysResource>(resourceMap.values());
    }

    @Transient
    public String getOrgsDescription() {
        if(ValidatorUtils.isArrayEmpty(sysOrganizationUsers)){
            return "";
        }
        List<String> orgNames = new LinkedList<String>();
        for(SysOrganizationUser organizationUser : sysOrganizationUsers){
            orgNames.add(organizationUser.getSysOrganization().getOrgName());
        }
        return StringUtils.join(orgNames, "，");
    }

    @Transient
    public String getRolesDescription() {
        if(ValidatorUtils.isArrayEmpty(sysOrganizationUsers)){
            return "";
        }
        List<String> roleNames = new LinkedList<String>();
        for (SysRole sysRole : sysRoles) {
            roleNames.add(sysRole.getRoleName());
        }
        return StringUtils.join(roleNames, "，");
    }

    @Transient
    public String getUserDescription() {
        String str = "";
        if (StringUtils.isNotBlank(userName) && StringUtils.isNotBlank(userNumber)){
            str = userName + "("+ userNumber +")";
        }
        return str;
    }

    @ManyToMany(fetch = FetchType.EAGER, mappedBy = "visibleUsers", cascade = {CascadeType.MERGE, CascadeType.PERSIST})
    @JSONField(serialize = false)
    public List<TDocumentCopy> getVisibleDocs() {
        return visibleDocs;
    }

    public void setVisibleDocs(List<TDocumentCopy> visibleDocs) {
        this.visibleDocs = visibleDocs;
    }

    @Column(name = "ORDER_NO")
    public Integer getOrderNo() {
        return orderNo;
    }

    public void setOrderNo(Integer orderNo) {
        this.orderNo = orderNo;
    }

    @Column(name = "IP_ADDRESS")
    public String getIpAddress() {
        return ipAddress;
    }

    public void setIpAddress(String ipAddress) {
        this.ipAddress = ipAddress;
    }
}
